#include <windows.h>
#include "CCharPacket.h"
#include "MySQL/mysql.h"
#include "CDb.h"
#include "CLinkshell.h"
#include "math.h"


CCharPacket::CCharPacket(CChar *schar, bool spawn) {
	unsigned int status = 0;
	unsigned short targ = 0;

	if(schar->m_pTarget != NULL) { 
		targ = schar->m_pTarget->getTargId();
	}
	targ *=2;

	this->type = 0x0D;
	this->size = 0x30;

	memset(data, 0, 92);

	memcpy(data, &(schar->m_id), sizeof(schar->m_id));

	unsigned short targId = schar->getTargId();
	memcpy(data+4, &targId, 2);
	if (spawn == true) {
		data[0x0A-4] = 0x1F;
		data[0x0B-4] = (unsigned char)schar->loc.p.rotation;
		memcpy(data+0x0C-4, &(schar->loc.p.x), sizeof(float)*3);
		memcpy(data+0x1a-4, &targ, sizeof(targ));
		memcpy(data+0x18-4, &(schar->movCount), sizeof(unsigned short));
		data[0x1C-4] = schar->m_speed;
		data[0x1D-4] = schar->m_speedAlt;
		data[0x1E-4] = (unsigned char)ceil(((float)schar->h.hp / (float)(schar->getMaxHp())) * 100);
		data[0x1F-4] = schar->getAnimation();
		status = ((schar->h.flags & 0xff000000) >> 5) + ((schar->h.flags & 0x000000ff) << 7);
		status |= (schar->getGender() * 0x8000);
		if(schar->getZone() == 0x2b) {			
			status = 1;	
		}
		memcpy(data+0x20-4, &(status), sizeof(int));

		data[0x22-4] = schar->h.nameFlag;
		if(schar->h.nameFlag & FLAG_GM) {
			data[0x23-4] = 0x04;
		}
		unsigned char red = 0x00;
		unsigned char green = 0x00;
		unsigned char blue = 0x00;
		CLinkshell * linkshell;
		linkshell = schar->getLinkshell();
		if(linkshell != NULL) {
			unsigned short lsColor = linkshell->getLsColor();
			red = (lsColor & 0xF);
			green = ((lsColor >> 4) & 0xF);
			blue = ((lsColor >> 8) & 0x0F);
		}
		// LSCOLOR (R G B)
		data[0x24-4] = (red * 16);
		data[0x25-4] = (green * 16);
		data[0x26-4] = (blue * 16);
		// END LS COLOR

		memcpy(data+0x3E-4, &(schar->l), sizeof(schar->l));
		memcpy(data+0x40-4, &(schar->l.head),  2);
		memcpy(data+0x42-4, &(schar->l.body),  2);
		memcpy(data+0x44-4, &(schar->l.hands), 2);
		memcpy(data+0x46-4, &(schar->l.legs),  2);
		memcpy(data+0x48-4, &(schar->l.feet),  2);
		memcpy(data+0x4A-4, &(schar->l.main),  2);
		memcpy(data+0x4C-4, &(schar->l.sub),   2);
		memcpy(data+0x4E-4, &(schar->l.range), 2);
		memcpy(data+0x50-4, &(schar->m_name),  16);

		memcpy(data+0x30-4, &(schar->m_costume), sizeof(schar->m_costume));

	} else {
		//Despawn
		data[0x0A-4] = 0x20;

	}
}

CCharPacket::~CCharPacket() {

}